package xml;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

import logger.Logger;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class ImportanceProvider {
	public static final ImportanceProvider INSTANCE = new ImportanceProvider();
	private HashMap<Integer, Importance> importances = new HashMap<>();
	
	private ImportanceProvider()
	{
		
		try
		{
			File f = new File("infoImportance.xml");
			if(!f.exists())
			{
				XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
				sortie.output(new Document(new Element("Importances")), new FileOutputStream("infoImportance.xml"));
				//f.createNewFile();
			}
			SAXBuilder sxb = new SAXBuilder();
			Document doc = sxb.build(f);
			for(Element el : doc.getRootElement().getChildren())
			{
				int imp = Integer.parseInt(el.getAttributeValue("Importance"));
				//boolean disp = Boolean.parseBoolean(el.getAttributeValue("Display"));
				int colR = Integer.parseInt(el.getAttributeValue("ColorR"));
				int colG = Integer.parseInt(el.getAttributeValue("ColorG"));
				int colB = Integer.parseInt(el.getAttributeValue("ColorB"));
				importances.put(imp, new Importance(imp, new Color(colR, colG, colB)));
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
	}
	
	public Importance getImportance(int imp)
	{
		if(importances.containsKey(imp))
			return importances.get(imp);
		
		//Importance inconnue
		Importance nw = new Importance(imp, Color.white);
		importances.put(imp, nw);
		saveAll();
		return nw;
	}
	
	public void removeImportance(int imp)
	{
		importances.remove(imp);
	}
	
	public Collection<Importance> getImportances()
	{
		return importances.values();
	}
	
	public void saveAll()
	{
		Element newRoot = new Element("Importances");
		
		for(Importance imp : importances.values())
		{
			Element impE = new Element("Imp");
			impE.setAttribute(new Attribute("Importance", ""+imp.importance));
			//impE.setAttribute(new Attribute("Display", ""+imp.display));
			impE.setAttribute(new Attribute("ColorR", ""+imp.color.getRed()));
			impE.setAttribute(new Attribute("ColorG", ""+imp.color.getGreen()));
			impE.setAttribute(new Attribute("ColorB", ""+imp.color.getBlue()));
			newRoot.addContent(impE);
		}
		
		enregistre(newRoot, "infoImportance.xml");
	}
	
	private static void enregistre(Element racine, String fichier)
	{
	   try
	   {
	      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
	      sortie.output(new Document(racine), new FileOutputStream(fichier));
	   }
	   catch (java.io.IOException e){
		   Logger.INSTANCE.logError(e);
	   }
	}
}
